import React from 'react';
// import ReactDOM from 'react-dom';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Link, withRouter, Route } from 'react-router-dom';
import { Tools, Icon, TextareaItem, Picker, Popover, ActivityIndicator } from 'weaver-mobile';
import { ListAdvanced, SearchAdvanced, TabPage, RouteLayout } from 'weaver-mobile-page';
import WfNoPermission from './no-permission/index'
import { forwardViewForm } from '../../util/common';
import * as EmSDK from '../../util/emSDK';
import './../../style/monitor.less'
import allStore from './../../stores'

const getLabel = Tools.getLabel;
const Item = Popover.Item;
@inject('wfMonitorStore')
@withRouter
@observer
export default class Monitor extends React.Component {

    componentDidMount() {
        const { wfMonitorStore } = this.props;
        const { listAdStore, defaultParams, getSopeList, getDataCallBack } = wfMonitorStore;
        getSopeList();
        listAdStore.getData({ url: '/api/workflow/monitor/getSessionkey', method: "POST", defaultParams }, getDataCallBack);
    }

    componentWillUpdate(nextProps) {
        const { wfMonitorStore, location } = nextProps;
        const { pathname = "" } = location;
        const { isShowTotal, setState, listAdStore } = wfMonitorStore;
        const { listViewStore } = listAdStore;
        if (pathname) {
            if (pathname.indexOf("/monitor") == 0) {
                EmSDK.controlEmTopNav({ title: getLabel(16758, "流程监控"), showCloseButton: false })
            }
        }
    }

    getListDom = () => {
        const { listAdStore,setTotalCount, showCheck, leftTreeValueArray, propsVisiable, defaultParams, getButtonName, showActionSheet, nowScope, scopeList, isShowTotal, totalCount } = this.props.wfMonitorStore;
        const { listViewStore, searchAdvancedStore } = listAdStore;
        const { form } = searchAdvancedStore;
        const { defaultValues, formData } = form;
        const { selectedRowKeys = [] } = listViewStore;
        //&& isShowTotal
        const extraPrompt = totalCount > 0  ? (<div style={{ textAlign: 'center', lineHeight: '30px', background: '#DFF1FF', color: '#55B1F9' }}>{getLabel(19661, "共有") + totalCount + getLabel(500597, "条流程")}</div>) : null;
        const Highlight = JSON.stringify(toJS(defaultValues)) === JSON.stringify(toJS(formData)) ? false : true;
        const searchPath = `${listAdStore.path}/SearchAdvanced`;
        const color = Highlight ? '#55B1F9' : '';
        let popover = (
            <Popover
                overlayClassName="fortest"
                overlayStyle={{ color: 'currentColor' }}
                visible={propsVisiable}
                mask={1}
                overlay={[
                    (<Item key="1" value="delete" >{scopeList[0].operatorText}</Item>),
                    (<Item key="2" value="delete" >{scopeList[4].operatorText}</Item>),
                    (<Item key="3" value="delete" >{scopeList[1].operatorText}</Item>),
                    (<Item key="4" value="delete" >{scopeList[2].operatorText}</Item>),
                    (<Item key="5" value="delete" >{scopeList[3].operatorText}</Item>),
                ]}
                align={{
                    overflow: { adjustY: 0, adjustX: 0 },
                    offset: [-10, 0],
                }}
                onVisibleChange={(visible) => {
                    const { setState } = this.props.wfMonitorStore;
                    setState({ propsVisiable: visible })
                }}
                onSelect={(key) => {
                    //[删除、暂停、撤销、启用、归档、收回、干预]
                    const { setState, scopeList, listAdStore } = this.props.wfMonitorStore;
                    const { listViewStore } = listAdStore;
                    if (key.key === "1") {
                        setState({ nowScope: scopeList[0] })
                    } else if (key.key === "2") {
                        setState({ nowScope: scopeList[4] })
                    } else if (key.key === "3") {
                        setState({ nowScope: scopeList[1] })
                    } else if (key.key === "4") {
                        setState({ nowScope: scopeList[2] })
                    } else if (key.key === "5") {
                        setState({ nowScope: scopeList[3] })
                    }
                    listViewStore.setState({ selectedRowKeys: [] })
                    setState({ propsVisiable: false, showCheck: true, })
                }}
            >
                <div style={{
                    height: '100%',
                    padding: '0 15px 0 0',
                    marginRight: '-15px',
                    alignItems: 'center',
                    display: "inline"
                }}
                >
                    <Icon type="ellipsis" />
                </div>
            </Popover>
        )
        let listDom = (
            <ListAdvanced
                store={listAdStore}
                hasAdvanceSerach
                extraPrompt={extraPrompt}
                rowKey="requestid"
                searchKey="requestname"
                treeKey="domid"
                dataFetchOptions={{
                    url: '/api/workflow/monitor/getSessionkey',
                    method: "POST",
                    params: {
                        ...defaultParams
                    }
                }}
                conditionFetchOptions={{
                    url: '/api/workflow/monitor/getConditionInfo',
                    method: 'POST',
                }}
                leftTreeFetchOptions={{
                    url: '/api/workflow/monitor/getTree',
                    method: 'POST',
                }}
                searchBarProps={{
                    showSelectButton: true,
                    selectText: getLabel(63, '类型'),
                    onSelectButtonClick: () => console.log('跳转到树'),
                    placeholder: getLabel(391119, '请输入流程标题'),
                    extraButton: [
                        {
                            key: 'advanced', show: <Link to={searchPath}>
                                <Icon
                                    type={`filter-o${Highlight ? '-hot' : ''}`}
                                    style={{ color }}
                                />
                            </Link>
                        },
                        { key: 'drop', show: popover },
                    ],
                    onExtraButtonClick: (key) => {

                        if (key === "drop") {
                            console.log("drop")
                        }
                    }
                }}
               
                leftTreeBrowserProps={{
                    searchBarProps: {
                        placeholder: getLabel(391153, '请输入类型/路径名称'),
                    },
                    valueArray: toJS(leftTreeValueArray),
                    onCleanUp: () => { console && console.log("onCleanUp") }
                }}
                showCheck={showCheck}
                buttonGroupData={[{
                    key: 'submit',
                    text: nowScope.operatorText,
                    onClick: showActionSheet,
                    className: selectedRowKeys.length > 0 ? 'wf-monitor-btn-primary' : "wf-monitor-btn-disabled"
                }]}
                onSearch={this.onSearch}
                onLeftTreeChange={this.onLeftTreeChange}
                onRowClick={this.onRowClick}
                onHideCheck={() => {
                    const { setState, listAdStore } = this.props.wfMonitorStore;
                    const { listViewStore } = listAdStore;
                    listViewStore.setState({ selectedRowKeys: [] })
                    setState({ showCheck: false })
                }}
                getDataCutom={true}
                onRefresh={() => {
                    const {  listAdStore } = this.props.wfMonitorStore;
                    const { dataKey } = listAdStore;
                    setTotalCount({ dataKey });
                }}
                getRowProps={this.getRowProps}
            />
        )
        return (listDom)
    }

    onSearch = () => {
        const { listAdStore, setState, getDataCallBack } = this.props.wfMonitorStore;
        const { searchAdvancedStore, listViewStore, searchParams } = listAdStore;
        // 搜索框等搜索数据
        let params = { ...searchParams };
        // 获取高级搜索参数
        if (searchAdvancedStore) {
            const { formParams } = searchAdvancedStore.form;
            params = { ...toJS(formParams) };
            if (params.typeid) {
                setState({
                    leftTreeValueArray: [
                        { id: 'type_' + params.typeid, name: params.typeidspan },
                    ],
                });
            } else if (params.workflowid) {
                setState({
                    leftTreeValueArray: [
                        { id: 'wf_' + params.workflowid, name: params.workflowidspan },
                    ],
                });
            } else if (!params.workflowid && !params.typeid) {
                setState({
                    leftTreeValueArray: [],
                });
            }
        }
        // 清除列表数据
        listViewStore.clearData();
        listViewStore.setState({ selectedRowKeys: [] });
        // 带参数请求列表数据
        listAdStore.getData({ url: '/api/workflow/monitor/getSessionkey', method: "POST", params: { ...params, fromwhere: "monitor" } }, getDataCallBack);
    }

    onLeftTreeChange = (domid, name, valueArray) => {
        const { listAdStore, setState } = this.props.wfMonitorStore;
        const fileds = {};
        if (/^wf_\d+/.test(domid)) {
            fileds.workflowid = { value: [{ id: domid.replace(/^wf_/, ''), name }] };
            fileds.typeid = { value: [] };
        }
        if (/^type_\d+/.test(domid)) {
            fileds.workflowid = { value: [] };
            fileds.typeid = { value: [{ id: domid.replace(/^type_/, ''), name }] };
        }
        if (domid === '') {
            fileds.typeid = { value: [] };
            fileds.workflowid = { value: [] };
        }
        // 同步树选中项到高级搜索的 from 中
        if (!listAdStore.searchAdvancedStore) {
            listAdStore.setState({
                searchAdvancedStore: new SearchAdvanced.Store({
                    route: listAdStore.path,
                    id: 'SearchAdvanced',
                }),
            });
            listAdStore.searchAdvancedStore.getData({
                url: 'api/workflow/monitor/getConditionInfo',
                method: 'POST',
                params: { ismobile: 1, _ec_device: true }
            }).then((form) => {
                if (listAdStore.searchParams.requestname) {
                    fileds.requestname = { value: listAdStore.searchParams.requestname };
                    form.updateFields(fileds);
                    this.onSearch();
                }
            });
        } else {
            listAdStore.searchAdvancedStore.form.updateFields(fileds);
            this.onSearch();
        }
        setState({ leftTreeValueArray: valueArray })
    }

    getRowProps = (rowData) => {
        //[删除、暂停、撤销、启用、归档、收回、干预]
        const { showCheck, nowScope, listAdStore } = this.props.wfMonitorStore;
        const { listViewStore } = listAdStore;
        if (showCheck) {
            let checkOp_arr = eval(toJS(rowData.randomFieldOp));
            if (checkOp_arr == undefined || checkOp_arr[nowScope.scope]) {
                let data = listViewStore.data;
                for (let i = 0; i < data.length; i++) {
                    if (data[i].requestid == rowData.requestid) {
                        data[i].disabled = false;
                    }
                }
                listViewStore.setState({ data: data });
                return { disabled: false }
            } else {
                let data = listViewStore.data;
                for (let i = 0; i < data.length; i++) {
                    if (data[i].requestid == rowData.requestid) {
                        data[i].disabled = true;
                    }
                }
                listViewStore.setState({ data: data });
                return { disabled: true }
            }
        }
    }

    onRowClick = (rowData) => {
        const { layout_noPermission, setState, loadListData, showCheck, listAdStore, nowScope } = this.props.wfMonitorStore;
        const { listViewStore } = listAdStore;
        let { selectedRowKeys } = listViewStore;
        if (showCheck) {
            let checkOp_arr = eval(toJS(rowData.randomFieldOp));
            if (checkOp_arr == undefined || checkOp_arr[nowScope.scope]) {
                if (selectedRowKeys.includes(rowData.requestid)) {
                    selectedRowKeys.splice(selectedRowKeys.indexOf(rowData.requestid), 1)
                    listViewStore.setState({ selectedRowKeys })
                } else {
                    listViewStore.setState({ selectedRowKeys: [...selectedRowKeys, rowData.requestid] })
                };
            }
        } else {
            //假如有流程干预权限
            let urlParams = {
                requestid: rowData.requestid,
                timestamp: Date.parse(new Date()),
            }
            if (rowData.hasOpenRightspan === "true") {
                urlParams.ismonitor = 1;
                if (rowData.hasInterveneRightspan === "true") urlParams.isintervenor = 1;
                forwardViewForm(urlParams, (arg = {}) => {
                    if (typeof arg === "string") {
                        arg = JSON.parse(arg);
                    }
                    let { isReturn } = arg;
                    if (isReturn == undefined) isReturn = false;
                    //关闭表单的回调--重刷当前页面
                    loadListData(isReturn);
                }, "/monitor");
            } else {
                setState({ workflowData: rowData })
                this.props.history.push(layout_noPermission.path)
            }
        }
    }

    render() {
        const { remarkEditorStore, layout_noPermission, workflowData, isShowLoading, hasLoad } = this.props.wfMonitorStore;
        if (hasLoad) {
            return (<div className="wf-monitor">
                {this.getListDom()}
                {isShowLoading && <ActivityIndicator
                    toast
                    text={getLabel(500408, "加载中...")}
                    animating={isShowLoading}
                />}
                <Route
                    key={layout_noPermission.id}
                    path={layout_noPermission.path}
                    render={() => (
                        <RouteLayout>
                            <div
                                key="WfNoPermission"
                                className="wm-route-layout wf-monitor-route-layout-page"
                            >
                                <WfNoPermission params={toJS(workflowData)} />
                            </div>
                        </RouteLayout>
                    )}
                />
            </div>)
        } else {
            return <div></div>
        }

    }
}
/**加载列表数据 */
export const loadListData = (isReturn) => {
    const {  setState, listAdStore, defaultParams, getDataCallBack } = allStore.wfMonitorStore;
    let params = { ...defaultParams };
    setState({ showCheck: false, leftTreeValueArray: [] });
    const { listViewStore, searchAdvancedStore } = listAdStore;
    if (listViewStore) {
        listViewStore.clearData();
    }
    // 获取高级搜索参数
    if (searchAdvancedStore) {
        const { formParams } = searchAdvancedStore.form;
        params = { ...params, ...formParams };
        // isReturn ? params = { ...params, ...formParams } : "";
        // !isReturn && searchAdvancedStore.form.updateFields(searchAdvancedStore.form.defaultValues)
    }
    listAdStore.getData({ url: '/api/workflow/monitor/getSessionkey', method: "POST", params: params }, getDataCallBack);
}
window.loadListData = loadListData;